package gw.com.android.ui.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.graphics.drawable.PaintDrawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.PopupWindow;

import com.gwtsz.gts2.hx.R;

import java.lang.reflect.Method;
import java.util.List;

import gw.com.android.ui.news.CalendarArgs;
import www.com.library.util.DeviceUtil;
import www.com.library.view.RecyclerViewDecoration;

/**
 * @author hubble on 2017/4/19.
 */
public class FilterPopView implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private Activity mActivity;
    private PopupWindow popWindow;
    private CountryAdapter mCountryAdapter;
    // 状态
    private CheckBox mCb_status_public, mCb_status_private;
    // 重要程度
    private CheckBox mCb_importance_1, mCb_importance_2, mCb_importance_3;
    // 类型
    private CheckBox mCbData, mCbEvent, mCbVacation;

    private CalendarArgs filterArgs = new CalendarArgs();
    private FilterCallback mCallback;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public FilterPopView(Activity activity, CalendarArgs args) {
        mActivity = activity;
        View view = View.inflate(activity, R.layout.view_pop_filter, null);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popWindow.setClippingEnabled(false);
        popWindow.setOutsideTouchable(false);
        popWindow.setTouchable(true);
        popWindow.setFocusable(true);
        popWindow.setAnimationStyle(R.style.popp_anim);
        popWindow.setBackgroundDrawable(new PaintDrawable(0x0000));

        RecyclerView mRcvCountry = view.findViewById(R.id.rcv_country);
        mRcvCountry.addItemDecoration(new RecyclerViewDecoration(DeviceUtil.instance().dip2px(10, activity)));
        GridLayoutManager mCountryManager = new GridLayoutManager(activity, 3);
        //mCountryManager.setAutoMeasureEnabled(true);
        mRcvCountry.setLayoutManager(mCountryManager);
        mCountryAdapter = new CountryAdapter(activity, args == null ? null : args.countries);
        mRcvCountry.setAdapter(mCountryAdapter);

        mCb_status_public = view.findViewById(R.id.cb_status_public);
        mCb_status_private = view.findViewById(R.id.cb_status_private);
        mCb_status_public.setOnCheckedChangeListener(this);
        mCb_status_private.setOnCheckedChangeListener(this);

        mCb_importance_1 = view.findViewById(R.id.cb_importance_1);
        mCb_importance_2 = view.findViewById(R.id.cb_importance_2);
        mCb_importance_3 = view.findViewById(R.id.cb_importance_3);
        mCb_importance_1.setOnCheckedChangeListener(this);
        mCb_importance_2.setOnCheckedChangeListener(this);
        mCb_importance_3.setOnCheckedChangeListener(this);

        mCbData = view.findViewById(R.id.cb_data);
        mCbEvent = view.findViewById(R.id.cb_event);
        mCbVacation = view.findViewById(R.id.cb_vacation);
        mCbData.setOnCheckedChangeListener(this);
        mCbEvent.setOnCheckedChangeListener(this);
        mCbVacation.setOnCheckedChangeListener(this);

        judgeIfSetStubSpace();

        view.findViewById(R.id.tv_reset).setOnClickListener(this);
        View confirm = view.findViewById(R.id.tv_confirm);
        confirm.setOnClickListener(this);
    }


    public void setCallback(FilterCallback callback) {
        this.mCallback = callback;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_reset:
                reset();
                break;
            case R.id.tv_confirm:
                hide();
                if (mCallback != null) {
                    mCallback.onConfirm(filterArgs);
                }
                break;
            default:
                break;
        }
    }

    private void reset() {
        filterArgs.countries = null;
        filterArgs.level = null;
        filterArgs.types = null;
        filterArgs.status = null;

        mCb_status_public.setChecked(false);
        mCb_status_private.setChecked(false);
        mCb_importance_1.setChecked(false);
        mCb_importance_2.setChecked(false);
        mCb_importance_3.setChecked(false);
        mCbData.setChecked(false);
        mCbEvent.setChecked(false);
        mCbVacation.setChecked(false);
        mCountryAdapter.reset();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void show(View parent) {
        if (!isShowing()) {
            judgeIfSetStubSpace();
            popWindow.showAtLocation(parent, Gravity.RIGHT, 0, 0);
        }
    }

    /**
     * 决定是否要设定透明空白区域（防止弹窗覆盖导航栏）；
     *
     * 为什么要封装成一个方法？
     * 因为 你有可能去操作 导航栏的隐藏显示，这里可以保证下一次弹窗一定是高度充满屏幕的。
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void judgeIfSetStubSpace() {
        final View contentView = popWindow.getContentView();
        ViewTreeObserver observer = contentView.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                contentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                Log.e("myHeight", "弹窗高度是:" + contentView.getMeasuredHeight());
                //检查弹窗高度 是不是 等于 整个屏幕的高度
                if (getHasVirtualKey(mActivity) == contentView.getMeasuredHeight()) {//如果相同，就设置空白区域高度,至于这里为什么不同，去炮轰手机厂家吧，鬼知道他们对原生系统做了什么。
                    View navigationStub = popWindow.getContentView().findViewById(R.id.navigation_stub);
                    ViewGroup.LayoutParams params = navigationStub.getLayoutParams();
                    params.height = getNavigationBarHeight(mActivity);
                    getScreenHeight(mActivity);
                    Log.e("myHeight", "导航栏高度是：" + params.height);
                    navigationStub.setLayoutParams(params);
                }//否则，就让空白区域继续为0高度

            }
        });


    }

    public boolean isShowing() {
        return popWindow.isShowing();
    }

    private void hide() {
        popWindow.dismiss();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_status_public:
                if (isChecked) {
                    mCb_status_private.setChecked(false);
                    filterArgs.status = CalendarArgs.STATUS_PUBLIC;
                } else {
                    filterArgs.status = null;
                }
                break;
            case R.id.cb_status_private:
                if (isChecked) {
                    mCb_status_public.setChecked(false);
                    filterArgs.status = CalendarArgs.STATUS_PRIVATE;
                } else {
                    filterArgs.status = null;
                }
                break;
            case R.id.cb_importance_1:
                if (isChecked) {
                    mCb_importance_2.setChecked(false);
                    mCb_importance_3.setChecked(false);
                    filterArgs.addLevel("1");
                } else {
                    filterArgs.removeLevel("1");
                }
                break;
            case R.id.cb_importance_2:
                if (isChecked) {
                    mCb_importance_1.setChecked(false);
                    mCb_importance_3.setChecked(false);
                    filterArgs.addLevel("2");
                } else {
                    filterArgs.removeLevel("2");
                }
                break;
            case R.id.cb_importance_3:
                if (isChecked) {
                    mCb_importance_1.setChecked(false);
                    mCb_importance_2.setChecked(false);
                    filterArgs.addLevel("3");
                } else {
                    filterArgs.removeLevel("3");
                }
                break;
            case R.id.cb_data:
                if (isChecked) {
                    filterArgs.addType(CalendarArgs.TYPE_DATA);
                } else {
                    filterArgs.removeType(CalendarArgs.TYPE_DATA);
                }
                break;
            case R.id.cb_event:
                if (isChecked) {
                    filterArgs.addType(CalendarArgs.TYPE_EVENT);
                } else {
                    filterArgs.removeType(CalendarArgs.TYPE_EVENT);
                }
                break;
            case R.id.cb_vacation:
                if (isChecked) {
                    filterArgs.addType(CalendarArgs.TYPE_VACATION);
                } else {
                    filterArgs.removeType(CalendarArgs.TYPE_VACATION);
                }
                break;
            default:
                break;
        }
    }

    public class CountryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private Context mContext;
        private List<String> mData;

        CountryAdapter(Context context, List<String> mData) {
            this.mContext = context;
            this.mData = mData;
        }

        public void reset() {
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new SimpleViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_country, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            final String country = getItem(position);
            // 填充数据
            SimpleViewHolder mHolder = (SimpleViewHolder) holder;
            mHolder.mRbCountry.setText(country);
            mHolder.mRbCountry.setOnCheckedChangeListener(null);
            mHolder.mRbCountry.setChecked(filterArgs.countries != null && filterArgs.countries.contains(country));
            mHolder.mRbCountry.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        if (filterArgs.countries == null || !filterArgs.countries.contains(country)) {
                            filterArgs.addCountry(country);
                        }
                    } else {
                        filterArgs.removeCountry(country);
                    }
                }
            });
        }

        private String getItem(int position) {
            if (mData != null && position >= 0 && position < mData.size()) {
                return mData.get(position);
            }
            return null;
        }

        @Override
        public int getItemCount() {
            return mData == null ? 0 : mData.size();
        }

        class SimpleViewHolder extends RecyclerView.ViewHolder {

            private CheckBox mRbCountry;

            SimpleViewHolder(final View itemView) {
                super(itemView);
                mRbCountry = itemView.findViewById(R.id.rb_country);
            }
        }
    }


    public interface FilterCallback {

        void onConfirm(CalendarArgs args);

    }

    /**
     * 导航栏的高度
     *
     * @param context
     * @return
     */
    private int getNavigationBarHeight(Activity context) {
        if (!isNavigationBarShow(context)) {//如果没有显示出来，就是0
            return 0;
        }
        // 显示出来了？那就从配置中去读取
        int rid = context.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
        if (rid != 0) {
            int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
            return context.getResources().getDimensionPixelSize(resourceId);
        } else {
            return 0;
        }
    }

    private boolean isNavigationBarShow(Activity context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = context.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            return realSize.y != size.y;
        } else {
            boolean menu = ViewConfiguration.get(context).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            return !menu && !back;
        }
    }

    //test

    /**
     * 获取屏幕的可绘制区域高度
     *
     * @param activity
     * @return
     */
    private int getScreenHeight(Activity activity) {
        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        Log.e("myHeight", "屏幕高度是：" + height);
        return height;
    }

    private void getViewHeight(final View v) {

    }

    /**
     * 得到屏幕的真实高度 比如：手机设置里面写的1920*1080；
     * 那么高度就是1920px
     * @param context
     * @return
     */
    /**
     * 通过反射，获取包含虚拟键的整体屏幕高度
     *
     * @return
     */
    private int getHasVirtualKey(Activity activity) {
        int dpi = 0;
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            dpi = dm.heightPixels;
            Log.e("myHeight", "包含虚拟按键的整体高度：" + dpi);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }


}
